package cn.com.tbshuda.gateway.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphO;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shuDa
 * @date 2021/12/7
 **/

@RefreshScope
@RestController
@RequestMapping("gateway")
public class HelloWorld2 {
    @Value("${test.name}")
    private String name;
    @RequestMapping("/get")
    public String hello(){
        return name;
    }

    public static void main(String[] args) {
        initRlue();
        while (true){
//            try(Entry hello_sentinel = SphU.entry("hello")) {
//                System.out.println("hello Word");
//                Thread.sleep(100);
//            } catch (BlockException e) {
//                System.out.println("我被限流了");
//            }catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            if(  SphO.entry("hello")){
                System.out.println("hello Word");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }finally {
                    SphO.exit();

                }
            }else{
                System.out.println("我被限流了");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }

    }
    public static void initRlue(){

        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        flowRule.setResource("dologin");
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setCount(2);
        rules.add(flowRule);
        FlowRuleManager.loadRules(rules);
    }
}
